package main

import (
	"log"
	"net/http"
	"strings"

	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool { return true },
}

func (s *Server) HandleWS(w http.ResponseWriter, r *http.Request) {
	name := r.URL.Query().Get("name")
	if name == "" {
		http.Error(w, "用户名不能为空", http.StatusBadRequest)
		return
	}
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("WebSocket 升级失败:", err)
		return
	}
	user := NewUser(conn, s, name)
	user.Online()
	defer func() {
		user.Offline()
		conn.Close()
	}()

	for {
		_, msg, err := conn.ReadMessage()
		if err != nil {
			break
		}
		user.DoMessage(string(msg))
	}
}

func splitN(s, sep string, n int) []string {
	parts := strings.SplitN(s, sep, n)
	for len(parts) < n {
		parts = append(parts, "")
	}
	return parts
}

func (u *User) handleGroupMessage(msg string) {
	parts := splitN(msg, "|", 4)
	cmd := parts[1]
	groupName := parts[2]
	switch cmd {
	case "create":
		u.Server.groupLock.Lock()
		if _, ok := u.Server.Groups[groupName]; ok {
			u.SendMsg("群组已存在")
		} else {
			u.Server.Groups[groupName] = &Group{
				Name:    groupName,
				Members: map[string]*User{u.Name: u},
			}
			u.CurrentGroup = groupName
			u.SendMsg("已创建并加入群组：" + groupName)
		}
		u.Server.groupLock.Unlock()
	case "join":
		u.Server.groupLock.Lock()
		group, ok := u.Server.Groups[groupName]
		if !ok {
			u.SendMsg("群组不存在")
		} else {
			group.Members[u.Name] = u
			u.CurrentGroup = groupName
			u.SendMsg("已加入群组：" + groupName)
		}
		u.Server.groupLock.Unlock()
	case "say":
		if u.CurrentGroup == "" {
			u.SendMsg("你尚未加入任何群组")
			return
		}
		u.Server.groupLock.RLock()
		group, ok := u.Server.Groups[u.CurrentGroup]
		if ok {
			for _, member := range group.Members {
				member.SendMsg("[群聊:" + group.Name + "] " + u.Name + ": " + parts[3])
			}
		}
		u.Server.groupLock.RUnlock()
	default:
		u.SendMsg("未知群组命令：group|create|群名 / group|join|群名 / group|say|群名|内容")
	}
}
